<template>
  <div>
    <div class="login">
    </div>
    <!--登录中间块-->
    <div class="login-mid">
      <!--
      @date:2024-10-30
      新版本方式
      初次加载的时候，需要加载资源，确保你网络正常
      -->

      <div class="login-mid-top">
        <div class="shadow-top-left"></div>
        <div class="shadow-top-right"></div>
      </div>

      <div class="login-mid-mid" ref="effet"></div>

      <!-- 倒计时提示 -->
      <div v-if="countdownText" style="text-align:center; color:#fff; margin-top:10px;">
        {{ countdownText }}
      </div>

      <div class="login-mid-bot">
        <div class="shadow-bot-left"></div>
        <div class="shadow-bot-right"></div>
      </div>
    </div>
  </div>

</template>
<script>
import { faceVerify, compareFaces } from "@/api/face/face.js";

export default {
  data() {
    return {
      isWaitingSecondPerson: false,
      videoWidth: 200,
      videoHeight: 200,
      msg:'',
      faceImgState:false,
      faceOption:{},
      faceStep: 1,
      faceImages: [],
      countdown: 5,            // 倒计时秒数
      countdownText: '',       // 倒计时提示文字
      countdownTimer: null     // 定时器句柄
    };
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.initFaceEffet();
      }, 1000); // 延迟一点时间确保DOM/摄像头准备好
    });
  },
  beforeDestroy(){
    if (this.$faceEffet){
      // 当页面销毁时，需要关闭
      this.$faceEffet.close();
    }
  },
  methods: {
    // 新版本调用方式
    // 新版本一共4种模式，人脸登录，人脸添加，睡眠检查，人脸打卡，更多有意思的参数可查看官网
    initFaceEffet() {
      this.$faceEffet.init({
        el: this.$refs.effet, // 直接传入html元素 也可以直接传入字符 'faceId'
        type: 'clockIn',// renlogin:人脸登录,addFace:人脸添加,sleepCheck:睡眠检查,clockIn:人脸打卡
        // callBack: this.callBack, // 阶段回调函数，会打印每个执行步骤，一般是在这个方法调用后端接口
        // callBack: this.doubleFaceCallBack, // 双人人脸识别的回调函数
        callBack: this.simpleDoubleFaceCallBack, // 双人人脸识别的回调函数(不判断是否同一个人)
      });
    },
    speak(message) {
      if ('speechSynthesis' in window) {
        const utter = new SpeechSynthesisUtterance(message);
        // 可选：设置语音参数
        utter.lang = 'zh-CN';
        utter.rate = 1;    // 语速
        utter.pitch = 1;   // 音调
        window.speechSynthesis.speak(utter);
      } else {
        console.warn("当前浏览器不支持语音合成");
      }
    },
    // 单人人脸识别的回调
    callBack(data){
      if (data.progressMessage === 'success'){ // 判断阶段是否成功
        let array = data.base64Array;
        if (!data.base64Array || data.base64Array.length === 0){
          return;
        }
        Promise.all(data.base64Array).then((base64Strings) => {
          // base64Strings 是一个人脸图片数组
          // 这个是模拟请求后端接口，请切换你自己的请求接口
          faceVerify({ imageBase: base64Strings[0] }).then(res => {
            if (res.code === 200){
              // 登录成功
              this.$faceEffet.close();
              localStorage.setItem("face_token",res.token);
              localStorage.setItem("username",res.name);
              this.$message.success(res.msg)
              this.speak("人脸识别成功，即将进入系统");  // 这里加语音提示
              setTimeout(() => {
                this.$router.push({path: "/faceInfo/face" });
              }, 1500);
            }else if (res.code === 201) {
              // 初始化人脸
              this.$faceEffet.restart()
              this.$message.success(res.msg)
            }else {
              // 登录失败 重启人脸容器，开始新的一轮验证
              this.$faceEffet.restart()
              this.$message.error(res.msg)
            }
          })
        }).catch((error) => {
          console.error("Error resolving promises:", error);
        });
      }
    },
    // 双人人脸识别的回调
    doubleFaceCallBack(data) {
      if (data.progressMessage !== 'success') return;
      if (this.isWaitingSecondPerson) return;

      let array = data.base64Array;
      if (!array || array.length === 0) return;

      Promise.all(array).then(base64Strings => {
        const currentBase64 = base64Strings[0];

        // 第一次识别
        if (this.faceStep === 1) {
          this.faceImages[0] = currentBase64;
          this.faceStep = 2;
          this.$message.success("第一人识别成功，请第二人准备识别");
          this.speak("第一人识别成功，请第二人准备识别"); // 语音提示
          this.countdown = 5;
          this.isWaitingSecondPerson = true;
          this.countdownText = `请第二人准备，${this.countdown} 秒后开始识别...`;

          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
              this.countdownText = '';
              this.isWaitingSecondPerson = false;
              this.$faceEffet.restart();
            } else {
              this.countdownText = `请第二人准备，${this.countdown} 秒后开始识别...`;
            }
          }, 1000);
          return;
        }

        // 第二次识别
        if (this.faceStep === 2) {
          this.faceImages[1] = currentBase64;

          // 检查是否是同一个人（调用后端）
          compareFaces({
            imageA: this.faceImages[0],
            imageB: this.faceImages[1]
          }).then(compareRes => {
            if (compareRes.code === 200) {
              if (compareRes.score < 80) {
                this.$message.success("第二人识别成功，两人为不同个体，开始提交验证");

                // 提交第一个人的验证信息
                faceVerify({ imageBase: this.faceImages[0] }).then(res1 => {
                  if (res1.code === 200) {
                    faceVerify({ imageBase: this.faceImages[1] }).then(res2 => {
                      if (res2.code === 200) {
                        // 两个人都验证成功
                        this.$message.success("双人识别成功");
                        this.$faceEffet.close();
                        this.speak("双人识别成功，即将进入系统");
                        // 做你自己的跳转或保存
                        setTimeout(() => {
                          this.$router.push({path: "/faceInfo/face" });
                        }, 1500);
                      } else {
                        this.$message.error("第二人验证失败：" + res2.msg);
                        this.resetFace();
                      }
                    });
                  } else {
                    this.$message.error("第一人验证失败：" + res1.msg);
                    this.resetFace();
                  }
                });

              } else {
                this.$message.error("识别结果为同一人，请更换第二人");
                this.speak("识别结果为同一人，请更换第二人");
                this.restartWithCountdown("请更换第二人", 5);
              }
            } else {
              this.$message.error("比对失败：" + compareRes.msg);
              this.restartWithCountdown("识别失败", 5);
            }
          });
        }
      });
    },
    // 双人人脸识别（不判断是否是同一人）
    simpleDoubleFaceCallBack(data) {
      if (data.progressMessage !== 'success') return;
      if (this.isWaitingSecondPerson) return;

      let array = data.base64Array;
      if (!array || array.length === 0) return;

      Promise.all(array).then(base64Strings => {
        const currentBase64 = base64Strings[0];

        // 第一次识别
        if (this.faceStep === 1) {
          this.faceImages[0] = currentBase64;
          this.faceStep = 2;
          this.$message.success("第一人识别成功，请第二人准备识别");
          this.speak("第一人识别成功，请第二人准备识别"); // 语音提示
          this.countdown = 5;
          this.isWaitingSecondPerson = true;
          this.countdownText = `请第二人准备，${this.countdown} 秒后开始识别...`;

          this.countdownTimer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.countdownTimer);
              this.countdownText = '';
              this.isWaitingSecondPerson = false;
              this.$faceEffet.restart();
            } else {
              this.countdownText = `请第二人准备，${this.countdown} 秒后开始识别...`;
            }
          }, 1000);
          return;
        }

        // 第二次识别
        if (this.faceStep === 2) {
          this.faceImages[1] = currentBase64;

          // 直接提交验证，不做是否为同一人比对
          faceVerify({ imageBase: this.faceImages[0] }).then(res1 => {
            if (res1.code === 200) {
              faceVerify({ imageBase: this.faceImages[1] }).then(res2 => {
                if (res2.code === 200) {
                  this.$message.success("双人识别成功");
                  this.$faceEffet.close();
                  this.speak("双人识别成功，即将进入系统");
                  // 根据需要跳转或执行其他操作
                  setTimeout(() => {
                    this.$router.push({path: "/faceInfo/face" });
                  }, 1500);
                } else {
                  this.$message.error("第二人验证失败：" + res2.msg);
                  this.resetFace();
                }
              });
            } else {
              this.$message.error("第一人验证失败：" + res1.msg);
              this.resetFace();
            }
          });
        }
      });
    },
    resetFace(reason = "人脸识别失败,请重新识别") {
      this.faceImages = [];
      this.faceStep = 1;
      this.isWaitingSecondPerson = false;
      this.speak(reason);
      this.restartWithCountdown(reason, 5);
    },
    restartWithCountdown(message = '即将重新识别', seconds = 5) {
      this.countdown = seconds;
      this.countdownText = `${message}，${this.countdown} 秒后开始识别...`;
      if (this.countdownTimer) clearInterval(this.countdownTimer);

      this.countdownTimer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(this.countdownTimer);
          this.countdownText = '';
          this.$faceEffet.restart();
        } else {
          this.countdownText = `${message}，${this.countdown} 秒后开始识别...`;
        }
      }, 1000);
    }
  }
};
</script>
<style>
@import "./index.css";
</style>
